package com.huitone.smspfm.oldclient.asclient.send;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import com.bin.common.utils.DateTimeUtils;
import com.bin.common.utils.StringUtils;
import com.huitone.smspfm.context.app.AppManager;
import com.huitone.smspfm.oldclient.app.AppStaticConfigs;
import com.huitone.smspfm.oldclient.asclient.SeqSmsFilterQueue;
import com.huitone.smspfm.oldclient.logger.ExtLogger;
import com.huitone.smspfm.oldclient.model.MtGroup;
import com.huitone.smspfm.oldclient.model.MtSms;
import com.huitone.smspfm.oldclient.store.MtGroupTmpStore;
import com.huitone.smspfm.oldclient.store.MtTmpStore;
import com.huitone.smspfm.socket.client.SmsClient;
import com.huitone.smspfm.socket.protocol.sgip.constant.CommandID;
import com.huitone.smspfm.socket.protocol.sgip.constant.Constant;
import com.huitone.smspfm.socket.protocol.sgip.message.Message;
import com.huitone.smspfm.socket.protocol.sgip.message.msgbody.Submit2;
import com.huitone.smspfm.socket.protocol.sgip.message.msghead.Head;
import com.huitone.smspfm.socket.utils.SerialUtils;

/**   
* @Title CrossFileMsgSendTask.java 
* @Package com.huitone.smspfm.oldclient.asclient.send 
* @Description TODO(用一句话描述该文件做什么) 
* @author ybliang   
* @date 2017年10月13日 下午1:43:07 
* @version V1.0   
*/
public class CrossFileMsgSendTask extends Thread {
	
	private final static ExtLogger logger = ExtLogger.create(CrossFileMsgSendTask.class);
	
	private long sleepTime = 1000;
	
	private long failIntevel = 600000; // 十分钟
	
	private SmsClient client = null;
	
	private boolean keepGoing = true;
	
	private SeqSmsFilterQueue filterQueue = SeqSmsFilterQueue.filterQueue;
	
	public CrossFileMsgSendTask(SmsClient client) {
		this.client = client;
	}

	@Override
	public void run() {
		
		logger.info("启动跨文件长短信合并发送线程。");
		
		while(isKeepGoing() && !this.isInterrupted()) {
			
			if (client.testConnectableNow(false)) {
				
				Iterator<Entry<String, MtGroup>> iterator = MtGroupTmpStore.get().entrySet().iterator();
				
				while(iterator.hasNext() && AppManager.isRunning() && !this.isInterrupted()) {
					
					Entry<String, MtGroup> entry = iterator.next();
					
					MtGroup mtGroup = entry.getValue();
					
					if (mtGroup == null) {
						continue;
					}
					
					if (mtGroup.sendAble()) {
						
						MtSms mtSms = mtGroup.merged();
						
							try {
								// 检查旧短信序号是否重复
								String oldSerialnoss = mtSms
										.getOldserialnos();

								boolean isRepeat = false; // 是否序号重复

								if (AppStaticConfigs.repeatseqsFilterOn) {
									List<String> serial = StringUtils
											.splitToList(oldSerialnoss,
													",");
									if (!StringUtils.isEmpty(serial)
											&& serial.size() > 0) {
										for (int i = 0; i < serial
												.size(); i++) {
											if (filterQueue
													.contains(serial
															.get(i))) {
												isRepeat = true;
												break;
											}
										}
									}
								}
								if (!isRepeat) {
								String serviceCode = AppStaticConfigs.serviceCode;
								if (AppStaticConfigs.isUseOldServiceCode) {
									serviceCode = mtSms.getServiceCode();
								}

								Submit2 submit = Submit2.build(
										mtSms.getMobileno(),
										AppStaticConfigs.srvNode, serviceCode,
										mtSms.getSendport(), 1,
										Constant.MessageCodingE.GBK.getValue(),
										Constant.MessageTypeE.SMS.getValue(),
										mtSms.getContent(),
										mtSms.getClientname(),
										mtSms.getOldserialnos());
								Head head = Head.build(submit.length(),
										CommandID.SGIP_SUBMIT2,
										AppStaticConfigs.codeRule, StringUtils
												.toIntegerP(DateTimeUtils
														.dateToStr(new Date(),
																"MMddHHmmss")),
										SerialUtils.getSerial());

								String serialNo = head.getSerialNo();

								mtSms.setSerialno(serialNo);
								mtSms.setSrvNode(AppStaticConfigs.srvNode);
								mtSms.setServiceCode(serviceCode);
								mtSms.setReportflag(1);
								mtSms.setCoderule(head.getSerialNoPart1());
								mtSms.setDatetime(head.getSerialNoPart2());
								mtSms.setSeqnumber(head.getSerialNoPart3());
								mtSms.setiSendTimes(1);
								mtSms.setLastSendTime(new Date());

								MtTmpStore.put(serialNo, mtSms);

								MtGroupTmpStore.remove(mtGroup.getGroupKey());

								boolean status = client.sendMsg(head, submit);

								if (!status) {
									client.testConnectableNow(true);
								}

								logger.submit(new Message(head, submit)
										.toString()
										+ ", 状态:"
										+ (status == true ? "提交成功" : "提交失败"));
								} else {
									logger.error("短信因序列号重复被过滤掉: "
											+ mtSms.toString());
								}

							} catch (Exception e) {
								String msg = "mtSms is null  serialno: "+mtGroup.getGroupKey();
								if(mtSms != null){
									msg = mtSms.toString();
								}
								logger.error("跨文件长短信发送时报错: msg :"	+ msg, e.getMessage());
							}
						
					} else {
						long currTime = System.currentTimeMillis();
						if (currTime - mtGroup.getLastAddTime().getTime() >= failIntevel) {
							// 超时没有组装完整则默认失败
							StringBuffer buffer = new StringBuffer();
							Iterator<Entry<Integer, MtSms>> items = mtGroup.getItems().entrySet().iterator();
							while(items.hasNext()) {
								buffer.append("\n");
								buffer.append(items.next().getValue().toString());
							}
							logger.warn("长短信等待组装时间超时,已读取长短信分段如下:" + buffer.toString());
							
							MtGroupTmpStore.remove(mtGroup.getGroupKey());
						}
					}
				}
			} else {
				logger.warn("[跨文件短信任务]目标地址:" + client.getServerIp() + ":" + client.getServerPort() + "不通!");
			}
			
			try {
				Thread.sleep(sleepTime);
			} catch (InterruptedException e) {}
		}
		
		logger.info("跨文件长短信发送线程退出。");
	}

	public SmsClient getClient() {
		return client;
	}

	public boolean isKeepGoing() {
		return keepGoing;
	}

	public void setKeepGoing(boolean keepGoing) {
		this.keepGoing = keepGoing;
	}

	@Override
	public void destroy() {
		this.setKeepGoing(false);
	}
}
